import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Alert, Row, Button, Divider, Modal, message, Col, Input, InputNumber } from 'antd';
import router from 'umi/router';
import StandardTable from '@/components/StandardTable';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import styles from '@/utils/utils.less';
import DiffModal from './DiffModal';

const { confirm } = Modal;
const FormItem = Form.Item;
const { TextArea } = Input;
@connect(({ handlediff, loading }) => ({
  loading: loading.models.handlediff,
  handlediff,
}))
@Form.create()
class Difference extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      selectedRows: [],
      selectedRowKeys: [],
      billAmo: 0, // Modal框中的账单总额
    };
  }

  componentDidMount() {}

  getList = (currentPage = 1, pageSize = 10) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'handlediff/fetchDiffData',
      payload: {
        pageArg: {
          currentPage,
          pageSize,
        },
      },
    });
  };

  // 点击复选框
  handleSelectRows = (selectedRows, selectedRowKeys) => {
    this.setState({ selectedRows, selectedRowKeys });
  };

  handleStandardTableChange = pagination => {
    this.getList(pagination.current, pagination.pageSize);
  };

  // 模态框显隐
  handleModalVisible = flag => {
    const { dispatch } = this.props;
    dispatch({
      type: 'handlediff/updateDiffModalData',
      payload: { diffVisible: !!flag },
    });
  };

  computed = values => {
    const { dispatch } = this.props;
    // '/osApi/insBillApi/amoRecalculation'
    dispatch({
      type: 'handlediff/handlediff',
      payload: values,
    });
  };

  detailClick = value => {
    const {
      dispatch,
      handlediff: {
        batchQuery: { assType },
      },
    } = this.props;
    const { insDifferentDataId, declAreaId, payWay, diffState, accuDifferentDataId } = value;
    dispatch({
      type: 'handlediff/fetchLsPkgName',
      payload: { declAreaId, payWay },
    });
    dispatch({
      type: 'handlediff/fetchJoinIdeList',
      payload: { areaId: declAreaId },
    });
    dispatch({
      type: 'handlediff/fetchDiffDataDet',
      payload: Number(assType) === 1 ? { insDifferentDataId } : { accuDifferentDataId },
    });
    dispatch({
      type: 'handlediff/updateDiffModalData',
      payload: { diffState },
    });
    this.handleModalVisible(true);
  };

  // 取消回盘
  cancleBack = () => {
    const {
      dispatch,
      handlediff: {
        batchQuery: { billId },
      },
    } = this.props;
    confirm({
      title: '取消回盘',
      icon: <ExclamationCircleOutlined />,
      content: '确定取消本次回盘吗？',
      okText: '继续',
      cancelText: '取消',
      onOk: () => {
        dispatch({
          type: 'handlediff/execCancelGoBack',
          payload: {
            billId,
          },
        });
      },
      onCancel: () => {},
    });
  };

  onOk = values => {
    const {
      dispatch,
      handlediff: {
        DifferenceData: {
          pageDto: { pagination },
        },
      },
    } = this.props;

    dispatch({
      type: 'handlediff/handlediff',
      payload: values,
      callback: res => {
        if (res) {
          this.handleModalVisible(false);
          this.getList(pagination.current, pagination.pageSize);
        }
      },
    });
  };

  onCancel = () => {
    this.handleModalVisible(false);
  };

  // 增加/修改回盘差额的modal
  handleDiffAmoModal = flag => {
    const { dispatch } = this.props;
    dispatch({
      type: 'handlediff/updateModelData',
      payload: { diffAmoVisible: !!flag },
    });
  };

  handleCancel = () => {
    this.handleDiffAmoModal(false);
  };

  diffAmoClick = () => {
    const {
      handlediff: {
        DifferenceData: { billAmo },
      },
    } = this.props;
    this.setState({
      billAmo,
    });
    this.handleDiffAmoModal(true);
  };

  handleOk = () => {
    const {
      dispatch,
      form,
      handlediff: {
        DifferenceData: {
          pageDto: { pagination },
        },
      },
    } = this.props;

    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        this.handleDiffAmoModal(false);
        dispatch({
          type: 'handlediff/updateDiffAmo',
          payload: values,
        })
          .then(res => {
            if (res.success) {
              message.success('操作成功！');
              this.getList(pagination.current, pagination.pageSize);
            }
          })
          .catch(error => {
            console.log(error);
          });
      }
    });
  };

  diffAmoChange = value => {
    const {
      handlediff: {
        DifferenceData: { billAmo, diffAmo },
      },
    } = this.props;
    const tempDiffAmo = diffAmo || 0;
    this.setState({
      billAmo: Number(billAmo - tempDiffAmo + value).toFixed(2),
    });
  };

  // 确认回盘
  confirmBack = () => {
    const {
      handlediff: {
        DifferenceData: { pageDto },
        batchQuery: { billId },
      },
      dispatch,
    } = this.props;
    const backFlag = pageDto.list.some(item => Number(item.diffState === 3)); // 有待处理差异
    if (backFlag) {
      message.warning('请选处理完列表所有差异数据再确认回盘');
    } else {
      confirm({
        // title: '确认回盘',
        // content: '确认回盘吗？已回盘的账单不能再取消回盘。',
        title: (
          <div>
            确认回盘吗？已回盘的账单不能再<span className="emphasize-text">取消回盘</span>。
          </div>
        ),
        icon: <ExclamationCircleOutlined />,
        onOk: () => {
          dispatch({
            type: 'handlediff/execGoBack',
            payload: {
              billId,
            },
          });
        },
        okText: '继续',
        cancelText: '取消',
      });
    }
  };

  render() {
    const { selectedRows, selectedRowKeys, billAmo } = this.state;
    const {
      loading,
      form: { getFieldDecorator },

      handlediff: {
        DifferenceData,
        diffModalData,
        diffAmoVisible,
        batchQuery: { assType },
        DifferenceData: { diffAmo, diffAmoCause },
      },
    } = this.props;
    const formItemLayout = {
      labelCol: { md: { span: 10 } },
      wrapperCol: { md: { span: 14 } },
    };
    const diffShow = Number(assType) === 1 ? styles.show : styles.hide;
    const renderDes = () => (
      <div>
        导入数据 : <span style={{ color: '#FAAD14' }}>{DifferenceData.importDiffCount}</span> 条,
        待处理差异: <span style={{ color: '#FAAD14' }}>{DifferenceData.unDealCount}</span> 条
        ，已处理差异：
        <span style={{ color: '#FAAD14' }}>{DifferenceData.dealCount}</span> 条 ，
        {DifferenceData.diffAmo || Number(DifferenceData.diffAmo) === 0 ? (
          <Fragment>
            <span>回盘差额：</span>
            <span style={{ color: '#FAAD14' }}>{DifferenceData.diffAmo}，</span>{' '}
            {/* <span>， 账单总额：</span>
            <span style={{ color: '#FAAD14' }}>{DifferenceData.payAmo}</span>
            <span> ，</span> */}
          </Fragment>
        ) : null}
        账单总额：<span style={{ color: '#FAAD14' }}>{DifferenceData.billAmo}</span>，
        <a onClick={() => this.diffAmoClick()}>
          {DifferenceData.diffAmo || Number(DifferenceData.diffAmo) === 0
            ? '修改回盘差额'
            : '增加回盘差额'}
        </a>
        {/* 差异总额：
        <span style={{ color: '#FAAD14' }}>{DifferenceData.diffAmoCount}</span>{' '} */}
      </div>
    );

    const columns = [
      {
        title: '姓名',
        dataIndex: 'empName',
        width: 120,
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
      },
      {
        title: '证件号',
        dataIndex: 'certNo',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
      },
      {
        title: '业务年月',
        dataIndex: 'busiYm',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
      },
      {
        title: '差额',
        dataIndex: 'diffAmo',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
      },
      {
        title: '差异状态',
        dataIndex: 'diffStateName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
      },
      {
        title: '险种',
        dataIndex: 'assNameArr',
        className: diffShow,
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: text => text || '--',
      },
      {
        title: '操作',
        dataIndex: 'n11',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder', width: 150 } }),
        render: (text, record) => (
          <span
            style={
              Number(record.diffState) === 3
                ? { color: '#E43B4C', cursor: 'pointer' }
                : { color: '#1890FF', cursor: 'pointer' }
            }
            onClick={() => this.detailClick(record)}
          >
            {' '}
            {Number(record.diffState) === 3 ? '差异处理' : '差异明细'}
          </span>
        ),
      },
    ];

    return (
      <div>
        <Alert
          description={renderDes()}
          type="warning"
          showIcon
          style={{ marginTop: 40, marginBottom: 20 }}
        />
        <StandardTable
          selectedRows={selectedRows}
          loading={loading}
          selectedRowKeys={selectedRowKeys}
          data={DifferenceData.pageDto}
          columns={columns}
          rowKey="insDifferentDataId"
          onSelectRow={this.handleSelectRows}
          onChange={this.handleStandardTableChange}
        />
        <Row type="flex" justify="center" style={{ marginTop: 24 }}>
          <Button
            onClick={() => {
              router.goBack();
            }}
          >
            关闭
          </Button>
          <Button style={{ marginLeft: 20, marginRight: 20 }} onClick={this.cancleBack}>
            取消回盘
          </Button>
          <Button type="primary" onClick={this.confirmBack}>
            确认回盘
          </Button>
        </Row>
        <Divider />
        <p>
          注：请您通过调整申报工资、政策组合、缴费人员类别使申报基数与回盘基数保持一致，如果以上三项不能使基数调整一致，调差后确认回盘，系统会自动将差额推送给对应客户的客户账单中。
          例如：最终差额为30元，对应客户账单将增加收取30元；最终差额为-20元，
          对应客户账单将减少收取20元。
        </p>
        <DiffModal
          diffModalData={diffModalData}
          loading={loading}
          computed={this.computed}
          onCancel={this.onCancel}
          onOk={this.onOk}
          assType={assType}
        />
        <Modal
          title="回盘差额"
          visible={diffAmoVisible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          destroyOnClose
          // width={800}
        >
          <Form>
            <Alert
              description="回盘计算进位规则导致账单总额有差异的，可使用差额将账单总额与实际回盘总额调整一致。"
              type="warning"
              showIcon
              // style={{ marginTop: 40, marginBottom: 20 }}
            />
            <Row style={{ marginTop: 30 }}>
              <Col span={18}>
                <FormItem {...formItemLayout} label="账单总额">
                  <Input placeholder="账单总额" disabled value={billAmo} />
                </FormItem>

                <FormItem {...formItemLayout} label="差额">
                  {getFieldDecorator('diffAmo', {
                    rules: [
                      {
                        required: true,
                        message: '填写金额格式不正确',
                        pattern: /^(?!^-0(\.0+)?$)-?((100(\.0{1,2})?)|[1-9]?\d(\.\d{1,2})?)$/,
                      },
                    ],

                    initialValue: diffAmo,
                  })(<InputNumber min={-10} max={10} step={0.01} onChange={this.diffAmoChange} />)}
                </FormItem>
                <FormItem {...formItemLayout} label="原因">
                  {getFieldDecorator('diffAmoCause', {
                    rules: [
                      {
                        required: true,
                        max: 50,
                        min: 5,
                        message: '请输入不少于5个字多于50个字的原因',
                      },
                    ],
                    initialValue: diffAmoCause,
                  })(
                    <TextArea
                      placeholder="请输入不少于5个字的原因"
                      autosize={{ minRows: 3, maxRows: 6 }}
                      min={5}
                      max={50}
                    />
                  )}
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Modal>
      </div>
    );
  }
}
export default Difference;
